﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Model.ModelsExt;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TencentCloud.Bm.V20180423.Models;
using TencentCloud.Common.Profile;

namespace AntUnion.FrameWork.Web.Controllers
{
    /// <summary>
    /// 个人信息控制器
    /// </summary>
    public class PersonalController : BaseController
    {
        /// <summary>
        /// 个人资料
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(string language = "user-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "user-en-US")
            {
                defaultLanguage = "en-US";
            }
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            if (crmUser == null)
            {
                return NotFound();
            }
            List<CrmUserInfo> crmUserInfos = crmService.GetCrmUserInfo(crmUserModel.Id);
            List<CrmKyc> crmkycList = crmService.GetCrmKyc();
            #region 个人信息
            List<CrmKyc> personalKycs = crmkycList.Where(k => k.Infotype == (int)CrmuserInfoType.Personal).ToList();
            CrmUserInfo personalUserInfos = crmUserInfos.OrderByDescending(k => k.CreateDate).FirstOrDefault(k => k.Type == (int)CrmuserInfoType.Personal);
            ViewBag.personalType = -1;
            if (personalUserInfos != null)
            {
                ViewBag.personalType = personalUserInfos.State;
                ViewBag.remark = personalUserInfos.Remarks;
            }
            if (personalUserInfos != null && !string.IsNullOrEmpty(personalUserInfos.Personal) && ViewBag.personalType != 1)
            {
                List<CrmKyc> personalInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(personalUserInfos.Personal);
                ViewBag.personalType = personalUserInfos.State;
                ViewBag.personalInformations = personalInformations;
            }
            else
            {
                ViewBag.personalInformations = personalKycs;
            }
            #endregion

            #region 财务信息
            List<CrmKyc> financialInKycs = crmkycList.Where(k => k.Infotype == (int)CrmuserInfoType.Financial).ToList();
            CrmUserInfo financialInUserInfos = crmUserInfos.OrderByDescending(k => k.CreateDate).FirstOrDefault(k => k.Type == (int)CrmuserInfoType.Financial);
            ViewBag.financialInType = -1;
            if (financialInUserInfos != null)
            {
                ViewBag.financialInType = financialInUserInfos.State;
                ViewBag.remark = financialInUserInfos.Remarks;
            }
            if (financialInUserInfos != null && !string.IsNullOrEmpty(financialInUserInfos.Financial) && ViewBag.financialInType != 1)
            {
                List<CrmKyc> financialInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(financialInUserInfos.Financial);
                //ViewBag.financialInType = financialInUserInfos.State;
                ViewBag.financialInformations = financialInformations;
            }
            else
            {
                ViewBag.financialInformations = financialInKycs;
                //List<InputModel> inputModels = new List<InputModel>();
                //foreach (CrmKyc crmKyc in financialInKycs)
                //{
                //    InputModel inputModel = new InputModel
                //    {
                //        name = crmKyc.Name,
                //        type = crmKyc.Type,
                //        value = ""
                //    };
                //    inputModels.Add(inputModel);
                //}
                //ViewBag.financialInformations = inputModels;
            }
            #endregion

            #region 身份信息
            List<CrmKyc> identityKycs = crmkycList.Where(k => k.Infotype == (int)CrmuserInfoType.Identity).ToList();
            CrmUserInfo identityUserInfos = crmUserInfos.OrderByDescending(k => k.CreateDate).FirstOrDefault(k => k.Type == (int)CrmuserInfoType.Identity);
            ViewBag.identityType = -1;
            if (identityUserInfos != null)
            {
                ViewBag.identityType = identityUserInfos.State;
                ViewBag.remark = identityUserInfos.Remarks;
            }
            if (identityUserInfos != null && !string.IsNullOrEmpty(identityUserInfos.Identity) && ViewBag.identityType != 1)
            {
                List<CrmKyc> identityInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(identityUserInfos.Identity);
                //ViewBag.identityType = identityUserInfos.State;
                ViewBag.identityInformations = identityInformations;
            }
            else
            {
                ViewBag.identityInformations = identityKycs;
                //List<InputModel> inputModels = new List<InputModel>();
                //foreach (CrmKyc crmKyc in identityKycs)
                //{
                //    InputModel inputModel = new InputModel
                //    {
                //        name = crmKyc.Name,
                //        type = crmKyc.Type,
                //        value = ""
                //    };
                //    inputModels.Add(inputModel);
                //}
                //ViewBag.identityInformations = inputModels;
            }
            #endregion

            List<PublicService.SystemConfigModel> systemConfigModels = publicService.GetSystemConfig();
            ViewBag.personalCenterWarmPrompt = systemConfigModels.FirstOrDefault(k => k.name == "personalCenterWarmPrompt" && k.language == defaultLanguage).value;
            ViewBag.financeWarmPrompt = systemConfigModels.FirstOrDefault(k => k.name == "financeWarmPrompt" && k.language == defaultLanguage).value;
            meunService.UpdateRead(crmUserModel.Id, 1);
            return View(crmUser);
        }

        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult EditCrmInfo(int type, List<InputModel> inputModels)
        {
            Result res = new Result();
            try
            {
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
                if (crmUser == null)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.accountNull;
                    return new JsonResult(res);
                }
                if (crmUser.State == (int)State.Disabled)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.disabledAccount;
                    return new JsonResult(res);
                }
                if (inputModels.Count == 0)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.userInfoNull;
                    return new JsonResult(res);
                }

                CrmUserInfo crmUserInfo = crmService.GetCrmUserInfo(crmUserModel.Id, type);
                if (crmUserInfo != null)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.hasCrmUserInfo;
                    return new JsonResult(res);
                }
                List<CrmKyc> subCrmKyc = new List<CrmKyc>();
                List<CrmKyc> crmKycs = crmService.GetCrmKyc(type);
                //验证数据
                foreach (InputModel model in inputModels)
                {
                    if(model.type=="IMG")
                    {
                        model.name = model.name.Replace("Img", "");
                    }
                    CrmKyc crmKyc = crmKycs.FirstOrDefault(k => k.ControlId == model.name);
                    if(crmKyc!=null)
                    {
                        if (crmKyc.Required == 0)
                        {
                            if (string.IsNullOrEmpty(model.value))
                            {
                                res.Code = 1;
                                res.Msg = LanguageConfig.confirmNoRequired;
                                return new JsonResult(res);
                            }
                        }
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.imformtionChange;
                        return new JsonResult(res);
                    }
                    crmKyc.Value = model.value;
                    subCrmKyc.Add(crmKyc);
                }
                int count = crmService.SubmitUserInfo(crmUserModel.Id, type, subCrmKyc);
                if (count > 0)
                {
                    res.Code = 0;
                    switch (type)
                    {
                        case 1:
                            res.Msg = LanguageConfig.personalApproval;
                            break;
                        case 2:
                            res.Msg = LanguageConfig.financialApproval;
                            break;
                        case 3:
                            res.Msg = LanguageConfig.identityApproval;
                            break;
                        default:
                            res.Msg = LanguageConfig.saveSuccess;
                            break;
                    }
                    return new JsonResult(res);
                }
                else
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.saveFailed;
                    return new JsonResult(res);
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 修改手机
        /// </summary>
        /// <returns></returns>
        public IActionResult Phone()
        {
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            return View(crmUser);
        }

        /// <summary>
        /// 修改手机
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePhone(string phone, string validCode)
        {
            Result res = new Result();
            try
            {
                CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
                if (crmUserModel == null)
                {
                    return NotFound();
                }
                if (string.IsNullOrEmpty(phone))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.phoneNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidPhone(phone))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.phoneError;
                    return new JsonResult(res);
                }
                CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
                //读取Session
                string code = publicService.GetCache<string>(crmUser.Email);
                if (code != null)
                {
                    if (code != validCode)
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.validCodeError;
                        return new JsonResult(res);
                    }
                    int count = crmService.UpdateCrmPhone(crmUserModel.Id, phone);
                    res.Code = 0;
                    res.Msg = LanguageConfig.updateSuccess;
                    return new JsonResult(res);
                }
                else
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeError;
                    return new JsonResult(res);
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 修改邮箱
        /// </summary>
        /// <returns></returns>
        public IActionResult Email()
        {
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            return View(crmUser);
        }

        /// <summary>
        /// 修改邮箱
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateEmail(string email, string validCode, string newEmail, string newValidCode)
        {
            Result res = new Result();
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            if (string.IsNullOrEmpty(email))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.emailNull;
                return new JsonResult(res);
            }
            if (!publicService.IsValidEmail(email))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.emailError;
                return new JsonResult(res);
            }
            if (string.IsNullOrEmpty(newEmail))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.newEmailNull;
                return new JsonResult(res);
            }
            if (!publicService.IsValidEmail(newEmail))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.newEmailError;
                return new JsonResult(res);
            }
            if (email == newEmail)
            {
                res.Code = 1;
                res.Msg = LanguageConfig.newEmailSame;
                return new JsonResult(res);
            }
            CrmUser hasEmail = crmService.GetCrmUser(newEmail);
            if (hasEmail != null)
            {
                res.Code = 1;
                res.Msg = LanguageConfig.hasAccount;
                return new JsonResult(res);
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            //读取Session
            string code = publicService.GetCache<string>(crmUser.Email);
            if (code != null)
            {
                if (code != validCode)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeError;
                    return new JsonResult(res);
                }
            }
            else
            {
                res.Code = 1;
                res.Msg = LanguageConfig.validCodeNull;
                return new JsonResult(res);
            }
            //读取Session
            string newCode = publicService.GetCache<string>(newEmail);
            if (newCode != null)
            {
                if (newCode != newValidCode)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.newValidCodeError;
                    return new JsonResult(res);
                }
            }
            else
            {
                res.Code = 1;
                res.Msg = LanguageConfig.newValidCodeNull;
                return new JsonResult(res);
            }
            int count = crmService.UpdateCrmEmail(crmUserModel.Id, newEmail);
            DeleteSessions("CrmUser");
            DeleteCookies("CrmUser");
            res.Code = 0;
            res.Msg = LanguageConfig.updateSuccess;
            return new JsonResult(res);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public IActionResult Password()
        {
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            return View(crmUser);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdatePassword(string password, string confirmPassword, string validCode)
        {
            Result res = new Result();
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            if (string.IsNullOrEmpty(password))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.passwordNull;
                return new JsonResult(res);
            }
            if (string.IsNullOrEmpty(confirmPassword))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.confirmPasswordNull;
                return new JsonResult(res);
            }
            if (password != confirmPassword)
            {
                res.Code = 1;
                res.Msg = LanguageConfig.passwordDifferent;
                return new JsonResult(res);
            }
            if (!publicService.IsValidPassword(password))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.passwordError;
                return new JsonResult(res);
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            //读取Session
            string code = publicService.GetCache<string>(crmUser.Email);
            if (code != null)
            {
                if (code != validCode)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeError;
                    return new JsonResult(res);
                }
                string encryptPwd = SecurityUtil.EncryptPwd(password);
                int count = crmService.UpdateCrmPassword(crmUserModel.Id, encryptPwd);
                res.Code = 0;
                res.Msg = LanguageConfig.updateSuccess;
                return new JsonResult(res);
            }
            else
            {
                res.Code = 1;
                res.Msg = LanguageConfig.validCodeError;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 修改交易密码
        /// </summary>
        /// <returns></returns>
        public IActionResult TradePassword()
        {
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            return View(crmUser);
        }

        /// <summary>
        /// 交易密码
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateTradePassword(string tradePassword, string confirmTadePassword, string validCode)
        {
            Result res = new Result();
            CrmUserModel crmUserModel = GetSession<CrmUserModel>("CrmUser");
            if (crmUserModel == null)
            {
                return NotFound();
            }
            if (string.IsNullOrEmpty(tradePassword))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.treadPasswordNull;
                return new JsonResult(res);
            }
            if (string.IsNullOrEmpty(confirmTadePassword))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.treadPasswordNull;
                return new JsonResult(res);
            }
            if (tradePassword != confirmTadePassword)
            {
                res.Code = 1;
                res.Msg = LanguageConfig.passwordDifferent;
                return new JsonResult(res);
            }
            if (!publicService.IsValidPassword(tradePassword))
            {
                res.Code = 1;
                res.Msg = LanguageConfig.passwordError;
                return new JsonResult(res);
            }
            CrmUser crmUser = crmService.GetCrmUser(crmUserModel.Id);
            //读取Session
            string code = publicService.GetCache<string>(crmUser.Email);
            if (code != null)
            {
                if (code != validCode)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeError;
                    return new JsonResult(res);
                }
                string encryptPwd = SecurityUtil.EncryptPwd(tradePassword);
                int count = crmService.UpdateCrmTradePassword(crmUserModel.Id, encryptPwd);
                res.Code = 0;
                res.Msg = LanguageConfig.submitSuccess;
                return new JsonResult(res);
            }
            else
            {
                res.Code = 1;
                res.Msg = LanguageConfig.validCodeError;
                return new JsonResult(res);
            }
        }

    }
}
